package com.hongji.lms5xxcommunicator.service.imp;

import com.hongji.lms5xxcommunicator.entity.RealtimeMetrics;
import org.springframework.stereotype.Service;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/** 统一的实时指标存取服务（所有扫描仪共用） */
@Service
public class RealtimeMetricsService {

    private final AtomicReference<RealtimeMetrics> latest = new AtomicReference<>();
    /** 提供“等待下一条”的能力（调试/测试用），容量有限避免阻塞 */
    private final BlockingQueue<RealtimeMetrics> queue = new LinkedBlockingQueue<>(32);

    public void update(RealtimeMetrics m) {
        latest.set(m);
        // best-effort 投递
        if (!queue.offer(m)) {
            queue.poll();
            queue.offer(m);
        }
    }

    /** 读取最新一条（可能是几百毫秒内的） */
    public RealtimeMetrics latest() {
        return latest.get();
    }

    /** 阻塞等待下一条（带超时；超时返回 null） */
    public RealtimeMetrics awaitNext(long timeoutMs) {
        try {
            return queue.poll(Math.max(1, timeoutMs), TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return null;
        }
    }
}
